package com.xiake.app.web.controller.file;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.xiake.core.constants.FileConstants;
import com.xiake.core.constants.WebUrlConstants;
import com.xiake.core.model.ReturnDataModel;

@Controller
@RequestMapping("file")
public class FileController {
	
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * TODO 上传
     * @param file
     * @param type
     * @return
     */
	@RequestMapping(value="update-img")
	@ResponseBody
	public ReturnDataModel uploadImg(MultipartFile file, Integer type){
		ReturnDataModel rdm = new ReturnDataModel(ReturnDataModel.RETURN_SUCCESS, "上传成功");
		String local = "/" + sdf.format(new Date()) + "/" + FileConstants.getPath(type);
        String path =  FileConstants.BASE_FILE_PATH + local;
        String fileName = file.getOriginalFilename();
        File targetFile = new File(path, fileName);  
        if(!targetFile.exists()){  
            targetFile.mkdirs();  
        }  
  
        //保存  
        try {  
            file.transferTo(targetFile);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("fileurl", WebUrlConstants.staticHost + local + "/" + fileName);
        rdm.setData(data);
		return rdm;
	}
}
